﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace kuaishou_crawler
{
    public class HttpUtils
    {


        public async static Task<string> RequestGetAsync(string url, Dictionary<string, string> header = null)
        {
            string result = "";
            using (HttpClient httpClient = new HttpClient())
            {
                if (header != null && header.Count > 0)
                {
                    foreach (var item in header)
                    {
                        httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }

                var responseMessage = await httpClient.GetAsync(url);
                result = await responseMessage.Content.ReadAsStringAsync();
                return result;
            }
        }



        public async static Task<string> RequestPostAsync(string postUrl, string postData = null, Dictionary<string, string> header = null)
        {
            string result = "";
            if (string.IsNullOrEmpty(postData))
                postData = "";
            using (HttpClient httpClient = new HttpClient())
            {
                if (header != null && header.Count > 0)
                {
                    foreach (var item in header)
                    {
                        httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }
                try
                {
                    var content = new StringContent(postData);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var responseMessage = await httpClient.PostAsync(postUrl, content);
                    result = await responseMessage.Content.ReadAsStringAsync();
                    return result;
                }
                catch (Exception ex)
                {

                    throw;
                }
            }
        }
    }
}